package com.sample.service.datastore.ex1;

import java.util.Date;
import java.util.Iterator;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;


public class EasyCRUD {

    static DatastoreService store = DatastoreServiceFactory.getDatastoreService();

    public static void create() {

        Iterator<Entity> it = read();
        if (it.hasNext()) {
            return;
        }

        Entity entity = new Entity("user");
        entity.setProperty("userId", "user1");
        entity.setProperty("name", "Taro");
        entity.setProperty("age", "16");
        entity.setProperty("date", new Date());

        store.put(entity);
    }

    public static Iterator<Entity> read() {
        PreparedQuery prepare = store.prepare(new Query("user"));
        return prepare.asIterator();
    }

    public static Entity singleRead() {
        PreparedQuery prepare = store.prepare(new Query("user"));
        return prepare.asSingleEntity();
    }

    public static void update() {
        Entity entity = singleRead();
        if (entity != null) {
            int age = Integer.parseInt((String) entity.getProperty("age")) + 1;
            entity.setProperty("age", String.valueOf(age));
            store.put(entity);
        }
    }

    public static void delete() {
        Entity entity = singleRead();

        if (entity != null) {
            store.delete(entity.getKey());
        }
    }
}
